package bot;
import java.util.ArrayList;
import java.util.Random;

public class WordNode{

	private String word;
	private ArrayList<WordNode> linkTo;
	public static boolean logOn = true;

	public WordNode(){
		this(null,false);
	}

	public WordNode(String value){
		this(value,false);
	}

	// The ultimate constructor!
	public WordNode(String value, boolean showLog){
		word = value;
		logOn = showLog;
		linkTo = null;
	}

	// Returns the word
	public String getWord(){
		return word;
	}

	public static void setLog(boolean showLog){
		logOn = showLog;
	}

	// Returns all other words that branch off of this word
	public ArrayList<WordNode> getWordList(){
		return linkTo;
	}

	// Returns true only if a the word is found to be linked to this word.
	// Null returns false.
	public boolean contains(String tester) {

		if (linkTo != null && tester != null) {
			for(int i = 0; i < linkTo.size(); i++) {
				String thisGuy = linkTo.get(i).getWord();
				if(thisGuy != null && thisGuy.compareToIgnoreCase(tester) == 0)
					return true;
			}
		}
		return false;
	}

	// Returns any one given word that branches off this word. Including NULL.
	public WordNode getRanNextWord(){
		Random rand = new Random();
		return linkTo==null ? null : linkTo.get(rand.nextInt(linkTo.size()));
	}

	// Adds a word to the list of words it links to.
	// It checks for duplicates. Including NULLs.
	public void addWord(WordNode newWord){

		// If this is the first word to be added,
		// create the list and add it.
		// Technically, this should never be called.
		if(linkTo == null) {
			linkTo = new ArrayList<WordNode>();
			linkTo.add(newWord);
			return;
		}

		// Checks for duplicate nulls
		if(newWord == null){
			for(int i = 0; i < linkTo.size(); i++) {
				if(linkTo.get(i) == null) {
					log("Warning @ WordNode.addWord(String) :: Duplicate NULLs detected.");
					return;
				}
			}
		// Checks for duplicate words
		} else {
			/*for(int i = 0; i < linkTo.size(); i++) {
				WordNode oldWord = linkTo.get(i);
				if(oldWord.getWord().compareToIgnoreCase(newWord.getWord()) == 0){
					log("Warning @ WordNode.addWord(String) :: Duplicate STRINGS detected.");
					return;
				}
			}*/
		}

		// It is now safe to add the new word
		linkTo.add(newWord);

	}


	private static void log(String message){
		if(logOn)
			System.out.println(message);
	}
	
	public String toString(){
		if(linkTo == null)
			return "[End]";
		
		String message = "[";
		
		for(int i = 0; i < linkTo.size(); i++) {
			if(i == linkTo.size()-1)
				message += linkTo.get(i).getWord();
			else
				message += linkTo.get(i).getWord() + " | ";
		}
		
		message += "]";
		return message;
	}

}
